package com.zues.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 测试域共享数据
 */
@Controller
public class ModelAndViewController {

    @RequestMapping("/toShare")
    public String testServletAPI(HttpServletRequest request) {
        request.setAttribute("testScope", "hello,servletAPI");
        return "share";
    }


    /**
     * ModelAndView有Model和View的功能
     * Model主要用于向请求域共享数据
     * View主要用于设置视图，实现页面跳转
     */
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView() {
        ModelAndView mav = new ModelAndView();
        //向请求域共享数据
        mav.addObject("testScope", "hello,ModelAndView");
        //设置视图，实现页面跳转
        mav.setViewName("share");
        return mav;
    }

    /**
     * 使用model向request域对象共享数据
     * @param model 视图模型
     * @return 视图名
     */
    @RequestMapping("/testModel")
    public String testModel(Model model){
        model.addAttribute("testScope","hello,model");
        return "share";
    }

    /**
     * 使用map向request域对象共享数据
     * @param map map
     * @return 视图名
     */
    @RequestMapping("/testMap")
    public String testMap(Map<String, Object> map){
        map.put("testScope","hello,map");
        return "share";
    }

    /**
     * 使用ModelMap向request域对象共享数据
     * @param modelMap modelMap
     * @return 视图名
     */
    @RequestMapping("/testModelMap")
    public String testModelMap(ModelMap modelMap){
        modelMap.addAttribute("testScope","hello,modelMap");
        return "share";
    }

    /**
     * 使用HttpSession向session域对象共享数据
     * @param session session
     * @return 视图名
     */
    @RequestMapping("/testSession")
    public String testSession(HttpSession session){
        session.setAttribute("testSessionScope","hello,session");
        return "share";
    }

    /**
     * 向application域共享数据
     * @param session session
     * @return 视图名
     */
    @RequestMapping("/testApplication")
    public String testApplication(HttpSession session){
        ServletContext application = session.getServletContext();
        session.setAttribute("testSessionScope","hello,session");
        application.setAttribute("testApplicationScope","hello,application");
        return "share";
    }
}
